﻿// ================================
// JEND v1.4.14
// extend of jQuery v1.3.2
// updated by jiangxiaoyang, 2011-04-14
// ================================
(function($) {
    // ----------------------------
    // String原型方法扩展
    $.extend(String.prototype, {
        'trim':  function() { 
            return this.replace(/(^\s*)|(\s*$)/g,'');
        },
        'ltrim': function() {
            return this.replace(/(^\s*)/g,''); 
        },
        'rtrim': function() { 
            return this.replace(/(\s*$)/g,'');
        },
        'left': function(len) {
            return this.substring(0, len);
        },
        'right': function(len) {
            if (this.length <= len) return this;
            return this.substring(this.length-len, this.length);
        },
        'reverse': function() {
            return this.split('').reverse().join('');
        },
        'getByteLength':  function() {
            return this.replace(/[^\x00-\xff]/ig, 'xx').length;
        },
        'subByte': function(len, s) {
            if (len<0 || this.getByteLength()<=len) {
                return this;
            }
            var str = this;
            str = str.substr(0,len).replace(/([^\x00-\xff])/g,"\x241 ").substr(0,len).replace(/[^\x00-\xff]$/,"").replace(/([^\x00-\xff]) /g,"\x241");
            return str + (s||'');
        },
        'textToHtml': function() { 
            return this.replace(/</ig,'&lt;').replace(/>/ig,'&gt;').replace(/\r\n/ig,'<br>').replace(/\n/ig,'<br>');
        },
        'htmlToText': function() { 
            return this.replace(/<br>/ig, '\r\n');
        },
        'htmlEncode': function() {
            var text = this; var re = {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'};
            for (i in re) text = text.replace(new RegExp(i,'g'), re[i]);
            return text;
        },
        'htmlDecode': function() {
            var text = this;
            var re = {'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'};
            for (i in re) text = text.replace(new RegExp(i,'g'), re[i]);
            return text;
        },
        'stripHtml': function() {
            return this.replace(/(<\/?[^>\/]*)\/?>/ig, ''); 
        },
        'stripScript': function() {
            return this.replace(/<script(.|\n)*\/script>\s*/ig, '').replace(/on[a-z]*?\s*?=".*?"/ig,'');
        },      
        'replaceAll': function(os, ns) {
            return this.replace(new RegExp(os,"gm"),ns); 
        },
        'escapeReg': function() {
            return this.replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\\x241');
        },
        'getQueryValue': function(name) {
            var reg = new RegExp("(^|&|\\?|#)" + name.escapeReg() + "=([^&]*)(&|\x24)", "");
            var match = this.match(reg);
            return (match) ? match[2] : '';
        },
        'getQueryJson': function() {            
            var query = this.substr(this.indexOf('?') + 1), params = query.split('&'), len = params.length, result = {}, key, value, item, param;
            for (var i=0; i < len; i++) {
                param = params[i].split('=');
                key = param[0];
                value = param[1];               
                item = result[key];
                if ('undefined' == typeof item) {
                    result[key] = value;
                } else if (Object.prototype.toString.call(item) == '[object Array]') {
                    item.push(value);
                } else {
                    result[key] = [item, value];
                }
            }
            return result;
        },
        'parseDate': function() {
            return (new Date()).parse(this.toString());
        },
        'parseJSON': function() {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(this.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + this.toString() + ')');
            } catch (e) {
                return false;
            }
        },
        'isURL': function() {
            return (new RegExp(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i).test(this.trim()));
        },
        'isEmail': function() {
            return (new RegExp(/^([_a-zA-Z\d\-\.])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/).test(this.trim()));
        },
        'isMobile': function() {
            return (new RegExp(/^(13|14|15|18)\d{9}$/).test(this.trim()));
        },
        'isPhone': function() {
            return (new RegExp(/^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/).test(this.trim()));
        },
        'isPostcode': function() {
            return (new RegExp(/^\d{6}$/).test(this.trim()));
        },
        'isLetters': function() {
            return  (new RegExp(/^[A-Za-z]+$/).test(this.trim()));
        },
        'isLowerCase': function() {
            return  (new RegExp(/^[a-z]+$/).test(this.trim()));
        },
        'isUpperCase': function() {
            return  (new RegExp(/^[A-Z]+$/).test(this.trim()));
        },
        'isChinese': function() {
            return (new RegExp(/^[\u4e00-\u9fa5]+$/).test(this.trim()));
        },
        'isIDCard': function() {
            //这里没有验证有效性，只验证了格式
            var r15 = new RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/);
            var r18 = new RegExp(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/);
            return (r15.test(this.trim()) || r18.test(this.trim()));
        },
        'formatToDSS': function() {
            var m = this.match(/^http(?:s)?:\/\/([^:\/]*)(:\d+)?([^\?]*)/);
            var a = '';
            if (m[1].match(/^[\d\.]*$/)) {
                a = '/ip/' + m[1];
            } else {
                var b = m[1].split('.');
                for (var i = b.length; i > 0; i--) {
                    a += '/' + b[i - 1];
                }
            }
            if (m[2]) {
                a += '/' + m[2];
            }
            return a + m[3];
        },
        'formatToDSSID': function() {
            return this.formatToDSS().replace(/\//g, '_');
        },
        'toMapObject': function(sep) {
            var sep = sep || '/';
            var s = this.split(sep);
            var d = {};
            var o = function(a, b, c) {
                if (c < b.length) {
                    if (!a[b[c]]) {
                        a[b[c]] = {};
                    }
                    d = a[b[c]];
                    o(a[b[c]], b, c + 1);
                }
            };
            o(window, s, 1);
            return d;
        },
        '_pad': function(width, char, side) {
            var str = [side?'':this, side?this:''];
            while (str[side].length < (width?width:0) && (str[side] = str[1] + (char||' ') + str[0]));
            return str[side];
        },
        'padLeft': function(width, char) {
            return this._pad(width, char, 0);
        },
        'padRight': function(width, char) {
            return this._pad(width, char, 1);
        },
        'toHalfWidth': function() {
            return this.replace(/[\uFF01-\uFF5E]/g, function(c) {
                return String.fromCharCode(c.charCodeAt(0) - 65248);
            }).replace(/\u3000/g," ");
        },
        'toCamelCase': function() {
            if (this.indexOf('-') < 0 && this.indexOf('_') < 0) {
                return this; 
            }
            return this.replace(/[-_][^-_]/g, function (match) {
                return match.charAt(1).toUpperCase();
            });
        },
        'format': function() {
            var result = this;
            if (arguments.length > 0) {
                parameters = $.makeArray(arguments);
                $.each(parameters, function(i, n) {
                    result = result.replace(new RegExp("\\{" + i + "\\}", "g"), n);
                });
            }
            return result;
        }
    });
    // Number原型方法扩展
    $.extend(Number.prototype, {
        'comma': function(length) {
            if (!length || length < 1) length = 3;
            source = (''+this).split(".");
            source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{'+length+'})+$)','ig'),"$1,");
            return source.join(".");
        },
        'randomInt': function(min, max) { 
            return Math.floor(Math.random() * (max - min + 1) + min);
        },
        'padLeft': function(width, char) {
            return (''+this).padLeft(width, char);
        },
        'padRight': function(width, char) {
            return (''+this).padRight(width, char);
        }
    });
    // Array原型方法扩展
    $.extend(Array.prototype, {
        'indexOf': function(item, it) {
            for (var i=0; i<this.length; i++) {
                if (item == ((it)?this[i][it]:this[i])) return i;
            }
            return -1;          
        },
        'remove': function(item, it) {
            this.removeAt(this.indexOf(item, it));
        },
        'removeAt': function(idx) {
            if (idx >= 0 && idx < this.length) {
                for (var i=idx; i<this.length-1; i++) {
                    this[i] = this[i+1];
                }
                this.length --;
            }
        },
        'sortby': function(it, dt, od) {
            // it: item name  dt: int, char  od: asc, desc
            var compareValues = function(v1, v2, dt, od) {
                if (dt == 'int') {
                    v1 = parseInt(v1);
                    v2 = parseInt(v2);
                } else if (dt == 'float') {
                    v1 = parseFloat(v1);
                    v2 = parseFloat(v2);
                }
                var ret = 0;
                if (v1 < v2) ret = 1;
                if (v1 > v2) ret = -1;
                if (od == 'desc') {
                    ret = 0 - ret;              
                }
                return ret;
            };
            var newdata = new Array();
            for (var i=0; i<this.length; i++) {
                newdata[newdata.length] = this[i];
            }
            for (var i=0; i<newdata.length; i++) {
                var minIdx = i;
                var minData = (it != '')?newdata[i][it]:newdata[i];
                for (var j=i+1; j<newdata.length; j++) {
                    var tmpData = (it != '')?newdata[j][it]:newdata[j];
                    var cmp = compareValues(minData, tmpData, dt, od);
                    if (cmp<0) {
                        minIdx = j;
                        minData = tmpData;
                    }
                }
                if (minIdx > i) {
                    var _child = newdata[minIdx];
                    newdata[minIdx] = newdata[i];
                    newdata[i] = _child;
                }
            }
            return newdata;
        }
    });
    // Date原型方法扩展
    $.extend(Date.prototype, {
        'parse': function(time) {           
            if (typeof(time)=='string') {               
                if (time.indexOf('GMT')>0 || time.indexOf('gmt')>0 || !isNaN(Date.parse(time))) {
                    return this.parseGMT(time);
                } else if (time.indexOf('UTC')>0 || time.indexOf('utc')>0 || time.indexOf(',')>0) {
                    return this.parseUTC(time);
                } else {
                    return this.parseCommon(time);
                }
            }
            return new Date();
        },
        'parseGMT': function(time) {
            this.setTime(Date.parse(time));
            return this;            
        },
        'parseUTC': function(time) {
            return (new Date(time));            
        },
        'parseCommon': function(time) {
            var d = time.split(/ |T/), d1 = d.length > 1 ? d[1].split(/[^\d]/) : [0, 0, 0], d0 = d[0].split(/[^\d]/);
            return new Date(d0[0]-0, d0[1]-1, d0[2]-0, d1[0]-0, d1[1]-0, d1[2]-0);
        },
        'dateAdd': function(type, val) {
            var _y = this.getFullYear();
            var _m = this.getMonth();
            var _d = this.getDate();
            var _h = this.getHours();
            var _n = this.getMinutes();
            var _s = this.getSeconds();
            switch(type) {
                case 'y':
                    this.setFullYear(_y + val);
                    break;
                case 'm':
                    this.setMonth(_m + val);
                    break;
                case 'd':
                    this.setDate(_d + val);
                    break;
                case 'h':
                    this.setHours(_h + val);
                    break;
                case 'n':
                    this.setMinutes(_n + val);
                    break;
                case 's':
                    this.setSeconds(_s + val);
                    break;
            }
            return this;
        },
        'dateDiff': function(type, date2) {
            var diff = date2 - this;
            switch(type) {
                case 'w':
                    return diff / 1000 / 3600 / 24 / 7;
                case 'd':
                    return diff / 1000 / 3600 / 24;
                case 'h':
                    return diff / 1000 / 3600;
                case 'n':
                    return diff / 1000 / 60;
                case 's':
                    return diff / 1000;
            }
        },
        'format': function(format) {
            if (isNaN(this)) return '';
            var o = {
                'm+': this.getMonth()+1,
                'd+': this.getDate(),
                'h+': this.getHours(),
                'n+': this.getMinutes(),
                's+': this.getSeconds(),
                'S':  this.getMilliseconds(),
                'W':  ["日", "一", "二", "三", "四", "五", "六"][this.getDay()],
                'q+': Math.floor((this.getMonth()+3)/3)
            }
            if (format.indexOf('am/pm')>=0) {
                format = format.replace('am/pm', (o['h+']>=12)?'下午':'上午');
                if (o['h+'] >= 12) o['h+'] -= 12;
            }
            if(/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("("+ k +")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
                }
            }
            return format;
        }
    });
    // ----------------------------
    // $.browser方法扩展
    $.extend($.browser, {
        'client': function() {
            return {
                width: document.documentElement.clientWidth,
                height: document.documentElement.clientHeight,
                bodyWidth: document.body.clientWidth,
                bodyHeight: document.body.clientHeight
            };
        },
        'scroll': function() {
            return {
                width: document.documentElement.scrollWidth,
                height: document.documentElement.scrollHeight,
                bodyWidth: document.body.scrollWidth,
                bodyHeight: document.body.scrollHeight,
                left: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
                top: Math.max(document.documentElement.scrollTop, document.body.scrollTop)
            };
        },
        'screen': function() {
            return {
                width: window.screen.width,
                height: window.screen.height
            };
        },
        'isIE6': $.browser.msie && $.browser.version == 6,
        'isMinW': function(val) {
            return Math.min($.browser.client().bodyWidth, $.browser.client().width) <= val;
        },
        'isMinH': function(val) {
            return Math.min($.browser.client().bodyHeight, $.browser.client().height) <= val;
        }
    });
    // ----------------------------
    // 获取DSS接口数据，源自JEND.DSS.get方法
    $.getDSS = function(url, params, onSuccess, onError) {
        if ($.isFunction(params)) {
            onError = onSuccess;
            onSuccess = params;
            params = null;          
        }
        var o = url.formatToDSS().toMapObject();
        if (params) url += (url.match(/\?/)?'&':'?')+ $.param(params);
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement("script");
        script.type = 'text/javascript';
        script.src = url;
        script.onload = script.onreadystatechange = function(){
            if ( !this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
                try {
                    if (o.$ && onSuccess) {
                        onSuccess(o.$);
                    } else {
                        if (onError) onError();
                    }
                } catch(e) {
                    if (onError) onError();
                }
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
            }
        };
        script.onerror = function() {
            if (onError) onError();
        };
        head.appendChild(script);
    };
    // 获取element属性的JSON值
    $.getRelData = function(element, attr) {
        var attr = attr||'rel';
        var p = {};
        if (element.attr(attr)) {
            var p_arr = element.attr(attr).split(';');
            for (var i=0; i<p_arr.length; i++) {
                if ($.trim(p_arr[i])=='') continue;
                var p_arr2 = p_arr[i].split(':');
                p[p_arr2[0]] = p_arr2[1];
            }
        };
        return p;
    };
    // 对象判断
    $.isObject = function(obj) {
        return (typeof obj=='object') && obj.constructor==Object;
    };
    $.isArray = function(obj) {
        return (typeof obj=='object') && obj.constructor==Array;
    };
    // ----------------------------
    // 绑定JEND.ui事件处理
    $.fn.bindJendUI = function(type, params) {
        if (this.size()==0) return;
        if (!JEND || !JEND.ui) return;
        var elm = this;
        if (JEND.ui[type]) {
            JEND.ui[type](elm, params);
        } else {
            JEND.load('ui', function() {
                setTimeout(function() {
                    if (!JEND.ui[type]) return;
                    JEND.ui[type](elm, params);
                }, 500);
            });
        }
    };
    // 获取tagName
    $.fn.tagName = function() { 
        if (this.length==0) return '';
        if (this.length>1) {
            var tagNames = [];
            this.each(function(i, el) {
                tagNames.push(el.tagName.toLowerCase());
            });
            return tagNames;
        } else {
            return this[0].tagName.toLowerCase();
        }
    };
    // ----------------------------
})(jQuery); 

// ================================
// JEND v1.0.1
// base on JEND v0.0.1 (j/lib/jend.js)
// updated by jiangxiaoyang, 2011-02-28
// ================================
var JEND = {};
// --------------------------------
(function($) {
    // ----------------------------
    // JEND v0.0.1 基本方法
    // ----------------------------
    JEND.Exception = function(pO, pID, pStr) {
        JEND.Exception[pO+'_'+pID] = pStr;
    };
    JEND.namespace = function(pStr) {
        if (typeof(pStr) === 'string') {
            pStr = '.' + pStr;
            JEND.lang.mapObject(pStr);
        }
    };
    JEND.flash = function(pSwf, pBoxID, pW, pH, pVer, pSetup, pFlashvars, pParams, pAttr) {
        pSetup = pSetup || false;
        pFlashvars = pFlashvars || false;
        pParams = pParams || false;
        pAttr = pAttr || false;
        JEND.load('swfobject', function() {
            swfobject.embedSWF(pSwf, pBoxID, pW, pH, pVer, pSetup, pFlashvars, pParams, pAttr);
        });
    };
    // ----------------------------
    JEND.lang = {};
    JEND.lang.mapObject = function(pStr, pSplit) {
        pSplit = pSplit || '.';
        return pStr.toMapObject(pSplit);
    };
    JEND.DOM = {};
    JEND.DOM.create = function(pTagName, pTagP, pText) {
        var dom = document.createElement(pTagName);
        if (typeof(pTagP)=='object') {
            for (var property in pTagP) {
                dom[property] = pTagP[property];
            }
        } else {
            pText = pTagP;
        }
        if (pText) {
            dom.appendChild(document.createTextNode(pText));
        }
        return dom;
    };
    JEND.DSS = {};
    JEND.DSS.get = function(pSrc, pCallback, pException) {
        if ($.isFunction(pException)) {
            $.getDSS(pSrc, null, pCallback, pException);
        } else if (typeof(pException)=='object') {
            $.getDSS(pSrc, pException, pCallback);
        } else {
            $.getDSS(pSrc, null, pCallback);
        }
    };
    JEND.DSS.formatToDSS = function(pStr) {
        return pStr.formatToDSS();
    };
    JEND.DSS.formatToDSSID = function(pStr) {
        return pStr.formatToDSSID();
    };
    JEND.cookie = {};
    JEND.cookie.load = function(tKey) {
        var tC = document.cookie.split('; ');
        var tO = {};
        var a = null;
        for (var i = 0; i < tC.length; i++) {
            a = tC[i].split('=');
            tO[a[0]] = a[1];
        }
        return tO;
    };
    JEND.cookie.set = function() {
        var d = new Date();
        var i = arguments.length;
        var key = i>0 ? arguments[0] : 'undefined';
        var value = i>1 ? arguments[1] : '';
        var expires = i>2 ? d.setTime(d.getTime() + (arguments[2] * 1000 * 60)) : null;
        var path = i>3 ? arguments[3] : null;
        var domain = i>4 ? arguments[4] : null;
        document.cookie = key + '=' + escape(value) + ((expires === null) ? '' : (';expires=' + d.toGMTString())) + ((path === null) ? '' : (';path=' + path)) + ((domain === null) ? '' : (';domain=' + domain));
        return this.get(key);
    };
    JEND.cookie.get = function(tKey) {
        if (this.load()[tKey]) {
            try {
                return decodeURI(this.load()[tKey]);
            } catch(e) {
                return unescape(this.load()[tKey]);
            }
        } else {
            return false;
        }
    };
    JEND.cookie.del = function(tKey) {
        if (this.get[tKey]) {
            var d = new Date();
            document.cookie = tKey + '=null; expires=' + d.setTime(d.getTime()).toGMTString();
        }
    };
    JEND.cookie.destroy = function() {
        var d = new Date();
        for (var key in this.load()) {
            document.cookie = this.load()[key] + ';expires=' + d.setTime(d.getTime()).toGMTString();
        }
    };
    // ----------------------------
    // JEND v1.0.1 扩展方法
    // 新增 JEND.debug()、JEND.load() 方法
    // 新增 JEND.json、JEND.base、JEND.util、JEND.page、JEND.ui等方法集合
    // ----------------------------
    // JEND.debug 调试
    JEND.debugMode = false;
    JEND.debugIndex = 0;
    JEND.debug = function(a, b) {
        if (!this.debugMode) return;
        this.debugIndex ++;
        if (typeof(console) == 'undefined') {
            if ($('#txtDebugLog').size()==0) $('body').append('<div style="position:absolute;top:0;left:0;right:0;z-index:9999;background-color:#eee;border-bottom:solid 1px #999;"><textarea id="txtDebugLog" style="display:block;width:980px;margin:5px auto;height:96px;line-height:16px;border:solid 1px #ccc;background-color:#ffc;"></textarea></div>');
            $('#txtDebugLog').val($('#txtDebugLog').val() + this.debugIndex.padLeft(4,'0') +'、'+ a +' = '+ b +'\n');
        } else {
            if (console && console.log) console.log(this.debugIndex.padLeft(4,'0') +'、'+ a, '=', b);
        }
    };
    // ----------------------------
    // JEND.load/JEND.loader 加载其他框架方法
    // JEND.load('util.dialog', 'pop', params);
    // JEND.load('swfobject', function(){});
    // JEND.load('http://……/demo.js', function(){});
    // JEND.load(['http://……/demo.js','http://……/demo2.js'], function(){});
    JEND.load = function(service, action, params) {
        if ($.isArray(service)) {
            var url = service.join(',');
            var urlsize = service.length;
            var status = JEND.loader.checkFileLoader(url);
            if (status == urlsize+1) {
                if (typeof(action)=='function') action();
            } else if (status > 0) {
                JEND.loader.addExecute(url, action);
            } else if (status == 0) {
                JEND.loader.addExecute(url, action);
                JEND.loader.fileLoader[url] = 1;
                JEND.debug('开始加载JS', url);
                for (var i=0; i<urlsize; i++) {
                    JEND.load(service[i], function() {
                        JEND.loader.fileLoader[url] ++;
                        if (JEND.loader.fileLoader[url] == urlsize+1) {
                            JEND.debug('完成加载JS', url);
                            JEND.loader.execute(url);
                        }
                    });
                }
            }
        } else if (JEND.loader.serviceLibs[service] && JEND.loader.serviceLibs[service].requires) {
            JEND.load(JEND.loader.serviceLibs[service].requires, function() {
                JEND.load.run(service, action, params);
            });
        } else {
            JEND.load.run(service, action, params);
        }
    };
    JEND.load.add = function(key, data) {
        if (JEND.loader.serviceLibs[key]) return;
        JEND.loader.serviceLibs[key] = data;
    };
    JEND.load.setPath = function(path) {
        JEND.loader.serviceBase = path;
    };
    JEND.load.run = function(service, act, params) {
        var action = (typeof(act)=='string') ? (function() {
            try {
                var o = eval('JEND.'+ service);
                if (o && o[act]) o[act](params);
            } catch(e) {}
        }) : act;
        if (JEND.loader.checkService(service)) {
            action();
            return;
        }
        // status:-1异常, 0未加载, 1开始加载, 2完成加载
        var url = JEND.loader.getServiceUrl(service);
        var status = JEND.loader.checkFileLoader(url);
        if (status == 2) {
            action();
        } else if (status == 1) {
            JEND.loader.addExecute(url, action);
        } else if (status == 0) {
            if ($('script[src='+url+']').size()>0) {
                JEND.loader.fileLoader[url] = 2;
                action();
            } else {                    
                JEND.loader.addExecute(url, action);
                JEND.loader.addScript(service);
            }
        } else {
            JEND.debug('加载异常', service);                    
        }
    };
    // ----------------------------
    JEND.loader = {};
    JEND.loader.fileLoader = {};
    JEND.loader.executeLoader = {};
    JEND.loader.serviceBase = '';
    JEND.loader.serviceLibs = {};
    JEND.loader.checkService = function(service) {
        try {
            if (service.isURL()) return false;
            var o = (service.indexOf('.')>0)?eval('JEND.'+service):eval(service);
            return (typeof(o)!='undefined');
        } catch(e) {
            return false;
        }
    };
    JEND.loader.checkFileLoader = function(url) {
        return (url!='') ? (this.fileLoader[url] || 0) : -1;
    };
    JEND.loader.getServiceUrl = function(service) {
        var url = '';
        if (service.isURL()) {
            url = service;
        } else if (this.serviceLibs[service]) {
            url = (this.serviceLibs[service].js.isURL()) ? this.serviceLibs[service].js : (this.serviceBase + this.serviceLibs[service].js);
        }
        return url;
    };
    JEND.loader.execute = function(url) {
        if (this.executeLoader[url]) {
            for (var i=0; i<this.executeLoader[url].length; i++) {
                this.executeLoader[url][i]();
            }
            this.executeLoader[url] = null;
        }
    };
    JEND.loader.addExecute = function(url, action) {
        if (typeof(action)!='function') return;
        if (!this.executeLoader[url]) this.executeLoader[url] = [];
        this.executeLoader[url].push(action);
    };
    JEND.loader.addScript = function(service) {
        var this_ = this;
        if (service.isURL()) {
            var url = service;
            this.getScript(url, function() {
                this_.fileLoader[url] = 2;
                JEND.debug('完成加载JS', url);
                JEND.loader.execute(url);
            });
        } else if (this.serviceLibs[service]) {
            if (this.serviceLibs[service].css) {
                var url = (this.serviceLibs[service].css.isURL()) ? this.serviceLibs[service].css : (this.serviceBase + this.serviceLibs[service].css);
                if (!this.fileLoader[url]) {
                    $('head').append('<link rel="stylesheet" type="text\/css"  href="'+  url +'" \/>');
                    this.fileLoader[url] = 1;
                    JEND.debug('开始加载CSS', url);
                }
            }
            if (this.serviceLibs[service].js) {
                var url = (this.serviceLibs[service].js.isURL()) ? this.serviceLibs[service].js : (this.serviceBase + this.serviceLibs[service].js);
                this.getScript(url, function() {
                    this_.fileLoader[url] = 2;
                    JEND.debug('完成加载JS', url);
                    JEND.loader.execute(url);
                });
            }
        }
    };
    JEND.loader.getScript = function(url, onSuccess, onError) {
        $.ajax({type:"GET", url:url, cache:true, success:onSuccess, error:onError, dataType:'script'});
        this.fileLoader[url] = 1;
        JEND.debug('开始加载JS', url);
    };
    // ----------------------------
    JEND.json = {};
    JEND.base = {};
    JEND.util = {};
    JEND.page = {};
    JEND.ui = {};
    // ----------------------------
    // JSON数据相关处理
    JEND.json.parse = function(data) {
        return (new Function("return " + data))();
    };
    JEND.json.stringify = function(obj) {
        var m = {'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"' :'\\"','\\':'\\\\'}, 
        s = {
            array:function(x){var a=['['],b,f,i,l=x.length,v;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=','}a[a.length]=v;b=true}}}a[a.length]=']';return a.join('')},
            'boolean':function(x){return String(x)},
            'null':function(x){return 'null'},
            number:function(x){return isFinite(x)?String(x):'null'},
            object:function(x){if(x){if(x instanceof Array){return s.array(x)}var a=['{'],b,f,i,v;for(i in x){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=','}a.push(s.string(i),':',v);b=true}}}a[a.length]='}';return a.join('')}return'null'},
            string:function(x){if(/["\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c}c=b.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})}return'\"'+x+'\"'}
        };
        return s.object(obj);
    };
    // ----------------------------
    // JEND.base，常用类集合
    // ----------------------------
    // StringBuilder: 字符串连接
    JEND.base.StringBuilder = function() {
        this._strings = [];
    };
    $.extend(JEND.base.StringBuilder.prototype, {
        append: function(str) {
            var aLen = arguments.length;
            for (var i=0; i<aLen; i++) {
                this._strings.push(arguments[i]);
            }
        },
        appendFormat: function(fmt) {
            var re = /{[0-9]+}/g;
            var aryMatch = fmt.match(re);
            var aLen = aryMatch.length;
            for (var i=0; i < aLen; i++) {
                fmt = fmt.replace(aryMatch[i], arguments[parseInt(aryMatch[i].replace(/[{}]/g, "")) + 1]);
            }
            this._strings.push(fmt);
        },
        toString: function() {
            return this._strings.join("");
        }
    });
    // ----------------------------
    // ImageLoader: 图像加载器
    JEND.base.ImageLoader = function(options) {
        this.options = $.extend({src:'', min:0.5, max:10, timer:0.1}, options || {});
        this.minTimeout = this.options.min * 1000;
        this.maxTimeout = this.options.max * 1000;
        this.intervalTimer = this.options.timer * 1000;
        this.theTimeout = 0;
        this.loadStatus = 0;
        this.loaderId = (new Date()).getTime();
        this.onLoad = this.options.onLoad || null;
        this.onError = this.options.onError || null;
        var m_this = this;
        this.init = function() {
            this.element = new Image();
            this.element.onload = function() {
                m_this.loadStatus = 1;
                if (m_this.onLoad) m_this.onLoad();
                JEND.debug('image onload', m_this.loaderId +': '+ this.width +','+ this.height);
            }
            this.element.onerror = function() {
                m_this.loadStatus = -1;
                if (m_this.onError) m_this.onError();
                JEND.debug('image onerror', m_this.loaderId);
            }
            this.element.src = this.options.src;
            this.startMonitor();
            JEND.debug('image init', m_this.loaderId);
        };
        this.startMonitor = function() {
            var m_this = this;
            setTimeout(function() {
                m_this.checkMonitor();
            }, this.minTimeout);
        };
        this.checkMonitor = function() {
            if (this.loadStatus != 0) return;
            this.theTimeout = this.minTimeout;
            this._monitor = setInterval(function() {
                m_this.theTimeout += 50;
                if (m_this.loadStatus != 0) {
                    clearInterval(m_this._monitor);
                } else if (m_this.element.complete) {
                    clearInterval(m_this._monitor);
                    m_this.loadStatus = 1;
                    if (m_this.onLoad) m_this.onLoad();
                    JEND.debug('image complete', m_this.loaderId +': '+ m_this.element.width +','+ m_this.element.height);
                } else if (m_this.theTimeout >= m_this.maxTimeout) {
                    clearInterval(m_this._monitor);
                    m_this.loadStatus = -1;
                    if (m_this.onError) m_this.onError();
                    JEND.debug('image timeout', m_this.loaderId);
                }
            }, m_this.intervalTimer);
        };
        this.init();
    };
    // ----------------------------
    // JEND.util，常用插件集合
    // ----------------------------
    // 遮盖层插件 JEND.util.overLayer
    JEND.util.overlayer = {};
    JEND.util.overlayer.id = 'util-overlayer';
    JEND.util.overlayer.status = false;
    // 显示遮盖层
    JEND.util.overlayer.showLayer = function(op, bg) {
        if (this.status) return false;
        op = (typeof(op)!='undefined')?op:0.5;
        bg = bg || '#fff';
        if ($('#'+this.id).length==0) $('body').append('<div id="'+this.id+'" style="width:100%;height:100%;position:absolute;top:0; left:0;right:0;bottom:0;display:none;z-index:9990;"></div>');
        $('#'+this.id).css({background:bg,filter:('alpha(opacity='+op*100+')'),opacity:op});
        this.setSize();
        this.status = true;
    };
    // 关闭遮盖层
    JEND.util.overlayer.hideLayer = function() {
        if (this.status) $('#'+this.id).css('display','none');
        this.status = false;
    };
    // 设置遮盖层大小
    JEND.util.overlayer.setSize = function() {
        $('#'+this.id).css({ width:'100%', height:$(document).height()+'px', display:'block'});
    };
    // 自适应屏幕调整遮盖层大小
    JEND.util.overlayer.resize = function() {
        if (this.status) { $('#'+this.id).css('display','none'); this.setSize(); }
    };
    // ----------------------------
    // 分享到其他网站
    JEND.util.share = {};
    JEND.util.share.sites = {
        'kaixin': {url:'http://www.kaixin001.com/repaste/share.php?rtitle={title}&rurl={url}&rcontent={content}'},
        'renren': {url:'http://share.renren.com/share/buttonshare.do?title={title}&link={url}'},
        'douban': {url:'http://www.douban.com/recommend/?title={title}&url={url}',pop:true,width:450,height:340},
        'sina': {url:'http://v.t.sina.com.cn/share/share.php?title={title}&url={url}&source=bookmark',pop:true,width:600,height:480},
        'qzone': {url:'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={url}'},
        't-qq': {url:'http://v.t.qq.com/share/share.php?url={url}&title={title}'}
    };
    JEND.util.share.openSite = function(site, title, url, content) {
        if (!this.sites[site]) return;
        var title = title || document.title;
        var url = url || document.location.href;
        var content = content || url;
        var shareUrl = this.sites[site].url.replace(/{title}/ig, encodeURIComponent(title)).replace(/{url}/ig, encodeURIComponent(url)).replace(/{content}/ig, encodeURIComponent(content));
        if (this.sites[site].pop) {
            var width = this.sites[site].width;
            var height = this.sites[site].height;
            var mx = (screen.availWidth - width)/2;
            var my = (screen.availHeight - height)/2;
            var feature = 'width='+width+',height='+height+',left='+mx+',top='+my;
            window.open(shareUrl, site, feature);
        } else {
            window.open(shareUrl, site);
        }
    };
    // ----------------------------
    // 页面切换等待提醒
    JEND.util.searchwaiting = {};
    JEND.util.searchwaiting.id = 'util-searchwaiting';
    JEND.util.searchwaiting.status = false;
    JEND.util.searchwaiting.init = function() {
        if ($('#'+this.id).size()==0) {
            $('body').append('<div id="'+ this.id+'" style="position:absolute;width:300px;height:220px;z-index:99999;display:none;"><img src="http://i3.eachimg.cn/2/i/cbt/101124/loadingEbay.gif" width="300" height="220" /></div>');
        }       
    };
    JEND.util.searchwaiting.showLayer = function() {
        JEND.util.overlayer.showLayer(0);
        this.init();
        this.status = true;
        this.resize();
    };
    JEND.util.searchwaiting.resize = function() {
        if (this.status) {
            $('#'+this.id).show();
            var _left = ($(window).width() - $('#'+this.id).width())/2;
            var _top = ($(window).height() - $('#'+this.id).height())/2;
            $('#'+this.id).css({
                left: $(document).scrollLeft() + Math.max(_left,20) +'px',
                top: $(document).scrollTop() + Math.max(_top,20) +'px'
            });
            if ($.browser.isIE6) $('#'+this.id).bindJendUI('HideOverElements', {element:'select,object'});
        }
    };
    $(window).resize(function() {
        JEND.util.overlayer.resize();
        JEND.util.searchwaiting.resize();
    });
    // ----------------------------
    // JEND.page，常用页面方法和页面处理集合
    // ----------------------------
    // 设为首页
    JEND.page.setHomepage = function() {
        var url = document.location.href;
        if (url.match(/_fromid=[\w]*/)) {
            url = url.replace(/_fromid=[\w]*/,'_fromid=userfavorite');
        } else {
            url += ((url.indexOf('?')>0)?'&':'?') +'_fromid=userfavorite';
        }
        if (document.all) {
            document.body.style.behavior = 'url(#default#homepage)';
            document.body.setHomePage(url);
        } else if (window.sidebar) {
            if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                } catch(e) {
                    alert('该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,\n然后将项 signed.applets.codebase_principal_support 值设为true');
                }
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBrance);
            prefs.setCharPref('browser.startup.homepage', url);
        }
    };          
    // 加入收藏
    JEND.page.addFavor = function() {
        var url = document.location.href;
        if (url.match(/_fromid=[\w]*/)) {
            url = url.replace(/_fromid=[\w]*/,'_fromid=userfavorite');
        } else {
            url += ((url.indexOf('?')>0)?'&':'?') +'_fromid=userfavorite';
        }
        var ctrlStr = ((navigator.userAgent.toLowerCase()).indexOf('mac')!=-1)?'Command/Cmd':'CTRL';
        if (document.all) {
            window.external.AddFavorite(url, document.title);
        } else if (window.sidebar) {
            window.sidebar.addPanel(document.title, url, '');
        } else {
            alert('您可以尝试通过快捷键'+ ctrlStr +' + D 加入到收藏夹~');
        }
    };
    // ----------------------------
})(jQuery);

// ============================
// 页头处理
// ============================
(function($) {
    // ----------------------------
    JEND.page.header = {};
    JEND.page.header.init = function() {
        this.initLogin();
        this.initCart();
        this.initSearchTabs();
        $('#headerkeywords').bindJendUI('InputDefault', {value:'看看正在流行什么...',color:'#999999'});
    };
    JEND.page.header.initLogin = function() {
        var l = 'http://login.eachnet.com/usr/login.do';
        var r = 'http://login.eachnet.com/usr/toRegister.do';
        var o = 'http://login.eachnet.com/usr/logout.do';
        var loginname = decodeURI(JEND.cookie.get('loginname')||'');
        var eachnetcookie = decodeURI(JEND.cookie.get('eachnetcookie')||'');
        var html = '您好<span>☺</span> ';
        if (loginname && eachnetcookie) {
            html += loginname +' <a href="'+o+'">退出</a>';
        } else if (loginname) {
            html += loginname +' <a href="'+l+'">[登录]</a> <a href="'+r+'">[注册]</a>';
        } else {
            html += '<a href="'+l+'">[登录]</a> <a href="'+r+'">[注册]</a>';
        }
        $('#headerlogin').html(html);
    };
    JEND.page.header.initCart = function() {
        if ($('#navchart').size()==0) return;
        $.getDSS('http://cart.eachnet.com/toolbar/shoppingcart.do', null, function(p) {
            var c = p[0].isc == 0 ? 'n': '';
            var html = ' <a id="navCartSum" rel="nofollow" href="http://cart.eachnet.com/MyShopingCart.do" target="_blank" className="'+ c +'">购物车(' + p[0].isc + ')</a> ';
            $('#navchart').append(html);
        });
    };
    JEND.page.header.initSearchTabs = function() {
        $('#headersearchtabs li').click(function() {
            var reldata = $(this).attr('rel') || '';            
            if (reldata) {
                var rel = reldata.split(',');
                $('#headersearchform')[0].pavilionCode.value = rel[0];
                $('#headersearchform')[0].action = rel[1];
                $('#headersearchtabs li').removeClass('on');
                $(this).addClass('on');
            }
        });
        var source = $('#headersearchtabs').attr('source');
        if (source == 'index') {
            $('#headersearchtabs li:eq('+((new Date()).getTime()%2)+')').click();
        }
    };
    // ----------------------------
})(jQuery);

// ============================
// 页面基本处理
// ============================
(function($) {
    // ----------------------------
    JEND.load.setPath('http://i3.eachimg.cn/2/');
    JEND.load.add('ui', { js:'j/eachnet/jend.ui.js?ver=1.4.2' });
    JEND.load.add('calendar', { js:'j/eachnet/ui/calendar.js?v=1.4.14', css:'c/utility/calendar.css?v=1.4.14' });
    JEND.load.add('util.dialog', { js:'j/eachnet/util/dialog.js?ver=1.3.24', css:'c/utility/dialog.css?ver=1.3.24' });
    JEND.load.add('swfobject', { js:'j/eachnet/lib/swfobject.js?ver=2.2' });
    // ----------------------------
    // 解决IE6下默认不缓存背景图片的bug
    if ($.browser.isIE6) try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
})(jQuery);
jQuery(document).ready(function($) {
    if (typeof(headerfunction)=='undefined') JEND.page.header.init();
    $('a.e-search-waiting, div.e-search-waiting a').bindJendUI('SearchWaiting');
});